const db = wx.cloud.database()
Page({
  data: {
    vote: {},
    selectvote: -1,
    isvote: false,
  },

  caculatevote: function() {
    db.collection('vote').doc(this.data.vote._id).get().then(optres => {
      var vote = optres.data
      console.log(vote)
      var total = 0
      for (var i = 0; i < vote.voteoptions.length; i++) {
        total = total + vote.voteoptions[i].num
      }
      for (var i = 0; i < vote.voteoptions.length; i++) {
        var percent = Math.round(vote.voteoptions[i].num / (total) * 10000) / 100.00 + "%"
        vote.voteoptions[i].percent = percent
      }
      this.setData({
        vote: vote
      })
    })
  },

  onLoad: function(options) {
    var id = options.id
    var userInfo = wx.getStorageSync('userInfo');
    db.collection('vote').doc(id).get().then(res => {
      var vote = res.data
      this.setData({
        vote: vote
      })
      db.collection('ticket').where({
        id: vote._id,
        _openid: userInfo.openid
      }).get().then(ticketres => {
        this.caculatevote()
        if (ticketres.data.length != 0) {
          this.setData({
            isvote: true,
            selectvote: ticketres.data[0].selectvote
          })
        } else {
          this.setData({
            isvote: !vote.available,
          })
        }
      })
    })
  },
  radioChange: function(event) {
    var selectvote = event.detail.value
    this.setData({
      selectvote: selectvote
    })
  },

  submit: function(event) {
    var userInfo = wx.getStorageSync('userInfo');
    if (this.data.selectvote != '') {
      db.collection('ticket').add({
          data: {
            id: this.data.vote._id,
            selectvote: this.data.selectvote
          }
        })
        .then(res => {
          wx.cloud.callFunction({
            name: 'vote',
            data: {
              _id: this.data.vote._id,
              selectvote: this.data.selectvote
            },
            success: res => {
              this.caculatevote()
              this.setData({
                isvote: true,
              })
            }
          })
        })
        .catch(console.error)
    } else {
      wx.showToast({
        title: '请输入选项...',
        icon: 'success',
        duration: 2000
      })
    }
  },
})